package calcsdk.nw;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;

public class AsyncWriter implements Runnable {

    PrintWriter out = null;
    LinkedList<String> queue = null;
    boolean work = true;
    private Thread thread = null;

    public AsyncWriter(String name, String dir) throws IOException {
        new File("results/"+ dir).mkdirs();
        FileWriter outFile = new FileWriter("results/"+ dir +"/"+name);
        out = new PrintWriter(outFile);
        queue = new LinkedList<String>();
        thread = new Thread(this);
        thread.setName("AsyncWriter");
        thread.start();
    }

    public synchronized void add(String str) {
        queue.add(str);
    }

    @Override
    public void run() {
        String text;

        while (work || queue.size() > 0) {
            try {
                text = queue.pollFirst();
            } catch (Exception e) {
                text = null;
                queue.clear();
            }
            while (text != null) {
                out.print(text);
                out.flush();
                try {
                    text = queue.pollFirst();
                } catch (Exception e) {
                    text = null;
                }
            }

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
            }
        }

        out.close();
    }

    public void stop() {
        work = false;
    }

    public void waitForStop() {
        if (work) {
            System.out.println("NOT STOPED");
        }
        while (thread.isAlive()) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException ex) {
            }
        }
    }

    public void stopAndWait() {
        stop();
        waitForStop();
    }

    public boolean isDone() {
        return thread.isAlive();
    }
}
